#include "yhargs.h"
#include "yherror.h"

#define DEFAULT_PORT 5555

int port    = -1;
int daemond = 0;
int optp;
int local;

static struct option opt[] = {
    {"port",   1, 0, 'p'},
    {"daemon", 0, 0, 'd'},
    {"localhost",0, 0, 'l'},
    {"help",   0, 0, 'h'},
    {0,0,0,0}
};
void usage(int argc, char **argv)
{
    err_msg("usage: %s [port] [option[=value]]...", argv[0]);
    err_msg("  -p, --port=number   Service port(range 1~65535, default %d)", DEFAULT_PORT);
    err_msg("  -d, --daemon        Daemon mode");
    err_msg("  -l                  Local service");
    err_msg("  -h, --help          Usage help");
}

void port_check()
{
    if (port <= 0 || port > 65535) {
        port = DEFAULT_PORT;
    }
}

void arguments(int argc, char **argv)
{
    char c;
    opterr = 1;
    while ((c = getopt_long(argc,argv,"p:dhl", opt, 0)) != -1) {
        switch (c) {
            case 'p':
                port = atoi(optarg);
                port_check();
                optp = 1;
                break;
            case 'd':
                daemond = 1;
                break;
            case 'l':
                local = 1;
                break;
            case 'h':
                usage(argc, argv);
                exit(0);
            case '?':
                err_quit("Try '%s --help' for more information.", argv[0]);
            default :
                usage(argc, argv);
                exit(1);
        }
    }
    if (optp == 0) {
        port = atoi(argv[argc-1]); // The last parameter
        port_check();
        optp = 1;
    }
}
